import { _decorator, Component, Node } from 'cc';
import { IView, IViewCtrl, IViewDataProccesor, TViewConfig, ViewId, ViewLayer } from '../../modules_common/view/IView';
import { ViewCtrlBase } from '../../modules_common/view/ViewCtrlBase';
const { ccclass, property } = _decorator;

export class ViewMgrData {
    ctrlMap: Map<ViewId, IViewCtrl> = new Map();
    dataProccesorMap: Map<ViewId, IViewDataProccesor> = new Map();
}

export class ViewMgr {

    private _uiRoot: Node = null;
    get uiRoot(): Node {
        return this._uiRoot;
    }
    set uiRoot(r: Node) {
        this._uiRoot = r;
    }

    private _data: ViewMgrData = new ViewMgrData();
    get data(): ViewMgrData {
        return this._data;
    }

    private _openViewId: Set<ViewId> = new Set();

    init() {

    }
    finit() {

    }

    static ctrlViewConfigKey = "viewConfig";
    static ctrlDepKey = "viewDep";

    register(id: ViewId, ctrl: IViewCtrl, dataProccesor: IViewDataProccesor): void {
        this.data.ctrlMap.set(id, ctrl);
        this.data.dataProccesorMap.set(id, dataProccesor);
    }

    open(viewId: ViewId, ...args: any[]): void {
        const ctrl = this.data.ctrlMap.get(viewId);
        if (!ctrl) {
            console.error('...... view mgr open,ctrl not found  ....... ', viewId)
            return;
        }
        const dataProccesor = this.data.dataProccesorMap.get(viewId);
        dataProccesor.setData(args);

        ctrl.onShow();

        this._openViewId.add(viewId);
    }

    close(viewId: number): void {
        const ctrl = this.data.ctrlMap.get(viewId);
        if (!ctrl) {
            console.error('...... view mgr close,ctrl not found  ....... ', viewId)
            return;
        }
        const dataProccesor = this.data.dataProccesorMap.get(viewId);
        dataProccesor.setData(null);

        ctrl.onHide();

        this._openViewId.delete(viewId);
    }

    addNodeToLayer(layer: ViewLayer, node: Node): void {
        const targetLayer = this.uiRoot.children[layer];
        if (!targetLayer) {
            console.error('...... view mgr add node to layer , error 1  ....... ',)
            return;
        }
        targetLayer.addChild(node);
    }

    removeNodeFromLayer(layer: ViewLayer, node: Node): void {
        const targetLayer = this.uiRoot.children[layer];
        if (!targetLayer) {
            console.error('...... view mgr remove node from layer , error 1  ....... ',)
            return;
        }
        targetLayer.removeChild(node);

    }


}







